from django.conf import settings
from rest_framework import serializers
from apps.accounts.serializers import UserSimpleSerializer
from .models import Chef, ChefCertificate, ChefReview, Dish, DishCategory, DjChef, DjChefVerification
from django.contrib.auth import get_user_model
import re


class ChefConsumerSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = ['id', 'nickname','real_name', 'avatar', 'specialty', 'bio', 'user_status', 'background','background_approved',
                 'rating', 'review_count', 'service_area', 'completed_orders', 'verification_status','phone_number']

class ChefCertificateSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChefCertificate
        fields = ['id', 'name', 'issuing_organization', 'year_obtained']

class ChefReviewSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)
    
    class Meta:
        model = ChefReview
        fields = ['id', 'user', 'rating', 'comment', 'created_at']
        read_only_fields = ['created_at']

# 这个就是视图需要的 ChefSerializer（与之前代码中的 ChefDetailSerializer 相同）
class ChefSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)
    certificates = ChefCertificateSerializer(many=True, read_only=True)
    reviews = ChefReviewSerializer(many=True, read_only=True)
    average_rating = serializers.FloatField(read_only=True)
    
    class Meta:
        model = Chef
        fields = [
            'id', 'user', 'bio', 'years_of_experience', 'specialty',
            'rating', 'average_rating', 'is_verified', 'address',
            'city', 'state', 'zip_code', 'certificates', 'reviews'
        ]
        read_only_fields = ['rating', 'average_rating']

# 其他序列化器保持不变...
class ChefBasicSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer()
    class Meta:
        model = Chef
        fields = ['id', 'user', 'specialty', 'rating']

class ChefCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Chef
        fields = ['bio', 'years_of_experience', 'specialty', 'address']

class DishCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = DishCategory
        fields = ['id', 'name', 'image']

class ChefCategorySerializer(serializers.ModelSerializer):
    """
    菜品分类序列化器
    用于厨师菜品分类列表展示
    """
    image = serializers.SerializerMethodField()

    class Meta:
        model = DishCategory
        fields = ['id', 'name', 'image', 'description']
        read_only_fields = fields

    def get_image(self, obj):
        if obj.image:
            return self.context['request'].build_absolute_uri(obj.image.url)
        return None

class DishSerializer(serializers.ModelSerializer):
    """
    菜品详细序列化器
    包含分类信息和厨师基本信息
    """
    category = ChefCategorySerializer(read_only=True)
    chef = serializers.SerializerMethodField()
    is_available = serializers.BooleanField(read_only=True)

    class Meta:
        model = Dish
        fields = [
            'id', 'name', 'description', 'price', 
            'image', 'category', 'chef',
            'is_spicy', 'prep_time', 'is_available',
            'created_at'
        ]
        read_only_fields = fields

    def get_chef(self, obj):
        from apps.accounts.serializers import UserSimpleSerializer
        return UserSimpleSerializer(obj.chef.user, context=self.context).data

    def get_image(self, obj):
        if obj.image:
            return self.context['request'].build_absolute_uri(obj.image.url)
        return None

class DjChefProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = ['id',
            'nickname', 'avatar', 'background', 'background_approved','user_status',
            'phone_number', 'balance', 'verification_status'
        ]
        read_only_fields = ['background_approved', 'verification_status']
        
    def validate_background(self, value):
        if value.size > 5 * 1024 * 1024:  # 5MB
            raise serializers.ValidationError("Background image too large (max 5MB)")
        if not value.content_type in ['image/jpeg', 'image/png']:
            raise serializers.ValidationError("Only JPEG/PNG images are allowed")
        return value
    
User = get_user_model()

class PhoneNumberSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11)
    
    def validate_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式不正确")
        return value

class SMSCodeSerializer(PhoneNumberSerializer):
    code = serializers.CharField(min_length=6, max_length=6)

class WechatLoginSerializer(serializers.Serializer):
    code = serializers.CharField(required=True)

class LoginResponseSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = ['id', 'nickname', 'avatar', 'is_verified', 'verification_status']

class ChangePhoneSerializer(serializers.Serializer):
    new_phone = serializers.CharField(
        max_length=11,
        min_length=11,
        help_text="新手机号"
    )
    sms_code = serializers.CharField(
        max_length=6,
        min_length=6,
        help_text="短信验证码"
    )
    
    def validate_new_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式不正确")
        
        if DjChef.objects.filter(phone_number=value).exists():
            raise serializers.ValidationError("该手机号已被注册")
            
        return value
    
class VerificationImageSerializer(serializers.Serializer):
    image_type = serializers.ChoiceField(
        required=True,
        choices=[
            ('id_card_front', '身份证正面'),
            ('id_card_back', '身份证反面'),
            ('health_certificate', '健康证明'),
            ('chef_certificate', '厨师资格证'),
            ('passport_image', '护照')
        ]
    )
    image = serializers.ImageField(required=True)
    openid = serializers.CharField(required=True)

class VerificationSubmitSerializer(serializers.ModelSerializer):
    # 显式声明前端传递的_url字段，确保不被过滤
    passport_image_url = serializers.URLField(required=False)
    id_card_front_url = serializers.URLField(required=False)
    id_card_back_url = serializers.URLField(required=False)

    class Meta:
        model = DjChefVerification
        fields = [
            # 保留模型字段
            'id_card_number',
            'id_card_front',
            'id_card_back',
            'passport_image',
            'health_certificate',
            'health_cert_expiry',
            'chef_certificate',
            'years_of_experience',
            'specialty',
            # 添加前端实际传递的_url字段
            'passport_image_url',
            'id_card_front_url',
            'id_card_back_url'
        ]
        # 所有字段均为非必填
        extra_kwargs = {f: {'required': False} for f in fields}
    
    def validate(self, data):
        """
        修复：处理可能为None的URL字段，避免strip()报错
        """
        # 1. 安全提取URL字段，默认值为空字符串
        id_card_front = data.get('id_card_front_url', '')
        id_card_back = data.get('id_card_back_url', '')
        passport_image = data.get('passport_image_url', '')
        
        # 2. 打印提取到的图片URL（调试用）
        print(f"提取到的身份证正面URL: {id_card_front!r}")  # !r显示原始值，包括空字符串
        print(f"提取到的身份证反面URL: {id_card_back!r}")
        print(f"提取到的护照图片URL: {passport_image!r}")
        
        # 3. 验证身份证组合：正反面URL都不为空
        has_valid_id_card = all([
            isinstance(id_card_front, str),
            id_card_front.strip() != '',  # 非空字符串
            isinstance(id_card_back, str),
            id_card_back.strip() != ''
        ])
        
        # 4. 验证护照组合：护照URL不为空
        has_valid_passport = all([
            isinstance(passport_image, str),
            passport_image.strip() != ''  # 非空字符串
        ])
        
        # 5. 必须满足其中一种组合
        if not has_valid_id_card and not has_valid_passport:
            raise serializers.ValidationError({
                "id_card_or_passport": "请提供有效的身份证（正反面图片）或护照（图片）"
            })
        
        # 6. 映射到模型字段
        if has_valid_id_card:
            data['id_card_front'] = id_card_front
            data['id_card_back'] = id_card_back
        if has_valid_passport:
            data['passport_image'] = passport_image
        
        return data


    def validate_id_card_number(self, value):
        if not re.match(r'^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$', value):
            raise serializers.ValidationError("身份证号格式不正确")
        return value

class VerificationStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = [
            'verification_status',
            'verification_submitted_at',
            'verification_processed_at'
        ]
        read_only_fields = fields

class SimpleChefSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)
    
    class Meta:
        model = Chef
        fields = ['id', 'user', 'specialty', 'rating']
        
#厨师小程序后台部分

class VdjChefSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)
    
    class Meta:
        model = Chef
        fields = ['id', 'user', 'specialty', 'rating', 'is_verified']
        read_only_fields = ['rating', 'is_verified']

class VdjChefCertificateSerializer(serializers.ModelSerializer):
    class Meta:
        model = ChefCertificate
        fields = ['id', 'name', 'issuing_organization', 'year_obtained']

class VdjChefReviewSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)
    
    class Meta:
        model = ChefReview
        fields = ['id', 'user', 'rating', 'comment', 'created_at']
        read_only_fields = ['created_at']

class VdjChefDetailSerializer(serializers.ModelSerializer):
    user = UserSimpleSerializer(read_only=True)
    certificates = VdjChefCertificateSerializer(many=True, read_only=True)
    reviews = VdjChefReviewSerializer(many=True, read_only=True)
    average_rating = serializers.FloatField(read_only=True)
    
    class Meta:
        model = Chef
        fields = [
            'id', 'user', 'bio', 'years_of_experience', 'specialty',
            'rating', 'average_rating', 'is_verified', 'address',
            'city', 'state', 'zip_code', 'certificates', 'reviews'
        ]
        read_only_fields = ['rating', 'average_rating']

class VdjDishCategorySerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()

    class Meta:
        model = DishCategory
        fields = ['id', 'name', 'image', 'description']
        read_only_fields = fields

    def get_image(self, obj):
        if obj.image:
            return self.context['request'].build_absolute_uri(obj.image.url)
        return None

class VdjDishSerializer(serializers.ModelSerializer):
    category = VdjDishCategorySerializer(read_only=True)
    chef = serializers.SerializerMethodField()
    is_available = serializers.BooleanField(read_only=True)

    class Meta:
        model = Dish
        fields = [
            'id', 'name', 'description', 'price', 
            'image', 'category', 'chef',
            'is_spicy', 'prep_time', 'is_available',
            'created_at'
        ]
        read_only_fields = fields

    def get_chef(self, obj):
        from apps.accounts.serializers import UserSimpleSerializer
        return UserSimpleSerializer(obj.chef.user, context=self.context).data

class VdjChefProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = [
            'nickname', 'avatar', 'background', 'background_approved',
            'phone_number', 'balance', 'verification_status'
        ]
        read_only_fields = ['background_approved', 'verification_status']
        
    def validate_background(self, value):
        if value.size > 5 * 1024 * 1024:  # 5MB
            raise serializers.ValidationError("Background image too large (max 5MB)")
        if not value.content_type in ['image/jpeg', 'image/png']:
            raise serializers.ValidationError("Only JPEG/PNG images are allowed")
        return value

class VdjPhoneNumberSerializer(serializers.Serializer):
    phone = serializers.CharField(max_length=11)
    
    def validate_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式不正确")
        return value

class VdjSMSCodeSerializer(VdjPhoneNumberSerializer):
    code = serializers.CharField(min_length=6, max_length=6)

class VdjWechatLoginSerializer(serializers.Serializer):
    code = serializers.CharField(required=True)


class WechatLoginSerializer(serializers.Serializer):
    code = serializers.CharField(required=True)
    nickName = serializers.CharField(required=False, allow_blank=True)
    avatarUrl = serializers.CharField(required=False, allow_blank=True)
    
class VdjLoginResponseSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = ['id', 'nickname', 'avatar', 'is_verified', 'verification_status']

class VdjChangePhoneSerializer(serializers.Serializer):
    new_phone = serializers.CharField(
        max_length=11,
        min_length=11,
        help_text="新手机号"
    )
    sms_code = serializers.CharField(
        max_length=6,
        min_length=6,
        help_text="短信验证码"
    )
    
    def validate_new_phone(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError("手机号格式不正确")
        
        if DjChef.objects.filter(phone_number=value).exists():
            raise serializers.ValidationError("该手机号已被注册")
            
        return value

class VdjVerificationImageSerializer(serializers.Serializer):
    image = serializers.ImageField()

class VdjVerificationSubmitSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChefVerification
        fields = [
            'id_card_number', 'id_card_front', 'id_card_back','passport_image',
            'health_certificate', 'health_cert_expiry', 'chef_certificate',
            'years_of_experience', 'specialty'
        ]
        extra_kwargs = {
            'id_card_front': {'required': True},
            'health_certificate': {'required': True},
            'chef_certificate': {'required': True}
        }

    def validate_id_card_front(self, value):
        return self._validate_image(value, max_size=5*1024*1024)  # 5MB

    def validate_health_certificate(self, value):
        return self._validate_image(value)

    def _validate_image(self, value, max_size=10*1024*1024):
        if value.size > max_size:
            raise serializers.ValidationError(f"图片大小不能超过 {max_size//1024//1024}MB")
        if not value.content_type.startswith('image/'):
            raise serializers.ValidationError("仅支持图片文件")
        return value

class VdjVerificationStatusSerializer(serializers.ModelSerializer):
    class Meta:
        model = DjChef
        fields = ['verification_status', 'verification_submitted_at', 'verification_processed_at']


#厨师身份审核后台管理


class VdjChefVerificationSerializer(serializers.ModelSerializer):
    id_card_front_url = serializers.SerializerMethodField()
    id_card_back_url = serializers.SerializerMethodField()
    health_certificate_url = serializers.SerializerMethodField()
    chef_certificate_url = serializers.SerializerMethodField()

    class Meta:
        model = DjChef
        fields = [
            'id', 'nickname', 'real_name', 'phone_number',
            'verification_status', 'verification_submitted_at',
            'verification_processed_at',
            'id_card_number', 
            'id_card_front_url', 'id_card_back_url',
            'health_certificate_url', 'chef_certificate_url',
            'years_of_experience', 'specialty'
        ]

    def _build_full_url(self, file_field):
        if file_field and hasattr(file_field, 'url'):
            request = self.context.get('request')
            if request:
                return request.build_absolute_uri(file_field.url)
            return f"{settings.BASE_URL}{file_field.url}"
        return None

    def get_id_card_front_url(self, obj):
        try:
            return self._build_full_url(obj.verification_info.id_card_front)
        except DjChefVerification.DoesNotExist:
            return None

    def get_id_card_back_url(self, obj):
        try:
            return self._build_full_url(obj.verification_info.id_card_back)
        except DjChefVerification.DoesNotExist:
            return None
        
class ChefAuthVerifySerializer(serializers.Serializer):
    """认证审核序列化器"""
    id_front_verified = serializers.BooleanField(required=True)
    id_back_verified = serializers.BooleanField(required=False)
    health_cert_verified = serializers.BooleanField(required=True)
    chef_cert_verified = serializers.BooleanField(required=True)
    approve = serializers.BooleanField(required=True)
    notes = serializers.CharField(required=False, allow_blank=True)

    def validate(self, data):
        """验证身份证反面是否必要"""
        if data.get('approve', False):
            chef = self.context['chef']
            if chef.verification_info.id_type == 'id_card' and not data.get('id_back_verified', False):
                raise serializers.ValidationError("身份证反面必须验证")
        return data